package com.h3bpm.kumhosunny.ehs.controller;

import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Entity.Data.Attachment.Attachment;
import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import OThinker.H3.Portal.webservices.BPMService;
import OThinker.H3.Portal.webservices.Entity.BPMServiceResult;
import OThinker.H3.Portal.webservices.Entity.DataItemParam;
import OThinker.H3.Portal.webservices.impl.BPMServiceImpl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


@Controller
@RequestMapping("/Portal/EhsCheckProblemsController")
public class EhsCheckProblemsController extends ControllerBase {

    private static final Logger LOGGER = LoggerFactory.getLogger(ControllerBase.class);

    private BPMService bpmService = new BPMServiceImpl();

    private ObjectMapper objectMapper = new ObjectMapper();


    @Override
    public String getFunctionCode() {
        return null;
    }

    //0be21fa7-a8e1-4187-ba9d-148b66e4b6af
    //http://localhost:8081/Portal/EhsCheckProblemsController/startEhsCheckSonProcess?instanceId=f80f488d-c146-488f-8178-752391c9cafa
    @RequestMapping("/startEhsCheckSonProcess")
    @ResponseBody
    public String startEhsCheckSonProcess(String instanceId) {

        String result = "200";


        //InstanceData
        try {
            InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);

            //数据封装
            HashMap<String, Object> valueTable = instanceData.getBizObject().getValueTable();
            List resultList = packProcessingData(instanceId, valueTable);

            //子流程发起用户
            String createPerson = (String) valueTable.get("CheckPerson");

            User nowUser = (User) getEngine().getOrganization().GetUnit(createPerson);


            for (int i = 0; i < resultList.size(); i++) {

                LOGGER.info("> EHS_CheckProblem: 发起子流程 >发起人:" + nowUser.getCode());
                BPMServiceResult bpmServiceResult = bpmService.StartWorkflow("H3", "Authine", "EHScheckrecord", nowUser.getCode(), false, (List<DataItemParam>) resultList.get(i));
                LOGGER.info("> " + objectMapper.writeValueAsString(bpmServiceResult));

            }

        } catch (Exception e) {
            result = "500";
            e.printStackTrace();
        }


        return result;
    }


    public List packProcessingData(String instanceId, HashMap<String, Object> valueTable) throws Exception {

        //返回子流程集合
        List resultList = new ArrayList();

        //获取子表数据
        BizObject[] checkProblemObjects = (BizObject[]) valueTable.get("ProblemList");

        //发起人
        User nowUser = (User) getEngine().getOrganization().GetUnit((String) valueTable.get("CheckPerson"));

        if (checkProblemObjects != null && checkProblemObjects.length > 0) {

            for (int i = 0; i < checkProblemObjects.length; i++) {

                HashMap<String, Object> objectHashMap = checkProblemObjects[i].getValueTable();


                String checkResult = (String) objectHashMap.get("CheckResult");

                //当前子表不合格，创建子流程
                if (!"".equals(checkResult) && "不合格".equals(checkResult)) {

                    List<DataItemParam> dataParam = new ArrayList<>();

                    //数据映射
                    dataParam.add(new DataItemParam("ActiveByName", "隐患排查-" + checkProblemObjects[i].getValueTable().get("CheckObject")));

                    dataParam.add(new DataItemParam("chechtime", valueTable.get("CheckDate")));
                    dataParam.add(new DataItemParam("checkstyle", valueTable.get("CheckType")));
                    dataParam.add(new DataItemParam("factory", valueTable.get("Factory")));
                    dataParam.add(new DataItemParam("arealevel1", valueTable.get("FirstRegion")));
                    dataParam.add(new DataItemParam("arealevel2", valueTable.get("SecondRegion")));
                    //映射负责人
                    String adminPerson = (String) valueTable.get("checkman");
                    User adminUser = (User) getEngine().getOrganization().GetUnit(adminPerson);
                    dataParam.add(new DataItemParam("checkpersons", adminUser.getName()));

                    dataParam.add(new DataItemParam("checkrecord", checkProblemObjects[i].getValueTable().get("Failed")));
                    //附件 ID
                    String fileId = (String) checkProblemObjects[i].getValueTable().get("FailedFileCode");

                    //当前不合格存在附件
                    if (!"".equals(fileId) && fileId != null) {

                        if (fileId.indexOf(';') != -1) {

                            String[] upFiles = fileId.split(";");

                            //JSONArray数组
                            JSONArray jsonArray = new JSONArray();

                            for (String file : upFiles) {

                                if (!"".equals(file) && file != null) {
                                    //根据附件ID取附件
                                    Attachment attachment = checkProblemObjects[i].GetAttachment(file);
                                    JSONObject jsonObject = new JSONObject();
                                    jsonObject.put("Code", attachment.getAttachmentID());
                                    jsonObject.put("ContentType", attachment.getContentType());
                                    jsonObject.put("Name", attachment.getFileName());
                                    jsonObject.put("Size",attachment.getContentLength());
                                    jsonObject.put("Url", "/Portal/ReadAttachment/Read?BizObjectSchemaCode=" + attachment.getBizObjectSchemaCode()
                                            + "&BizObjectID=" + attachment.getBizObjectId() + "&AttachmentID=" + attachment.getAttachmentID());


                                    jsonArray.add(jsonObject);

                                }

                            }
                            //映射入字段
                            dataParam.add(new DataItemParam("HideFileCode", jsonArray.toString()));


                        }


                    }
                    //放入list集合
                    resultList.add(dataParam);

                }

            }


        }

        return resultList;

    }
}
